package com.jianbo.proxy.conf;

import java.io.InputStream;
import java.util.Properties;

import org.smartboot.http.common.logging.Logger;
import org.smartboot.http.common.logging.LoggerFactory;

import com.jianbo.proxy.util.FileUtil;

import lombok.Getter;

public class PropertiesConf {

    private static Logger logger = LoggerFactory.getLogger(PropertiesConf.class);

    public static PropertiesConf instance;
    
    public static PropertiesConf getInstance() {
        return instance;
    }

    public static PropertiesConf getInstance(ArgsConf args) {
        if(instance == null) {
            instance = new PropertiesConf(args);
        }
        return instance;
    }

    ArgsConf argsConf;
    Properties properties;
    public PropertiesConf(ArgsConf argsConf) {
        this.argsConf = argsConf;
        this.loadProperties();
    }
    
    private void loadProperties() {
        String propFile = argsConf.getPropFile();
        properties = new Properties();
        try {
            InputStream inStream = FileUtil.readStream(propFile);
            String propContent = FileUtil.readString(propFile);
            logger.info(propFile);
            logger.info("读取配置文件：\n" + propContent);
            properties.load(inStream);
            loadProp();

            logger.info("静态资源是否开启缓存：" + staticCache());
        } catch  (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public boolean staticCache() {
        return isStaticCache();
    }

    public String getProperty(String key) {
        return properties.getProperty(key);
    }

    public int getInt(String key) {
        return Integer.valueOf(getProperty(key));
    }

    public boolean getBool(String key) {
        String prop = getProperty(key);
        if("true".equals(prop)) {
            return true;
        }
        return false;
    }

    @Getter
    private int port;
    @Getter
    private String welcome;
    @Getter
    private boolean staticCache;
    @Getter
    private String encoding;
    @Getter
    private boolean presetApi;

    private void loadProp() {
        port = getInt("port");
        welcome = getProperty("welcome");
        staticCache = getBool("static-cache");
        encoding = getProperty("encoding");
        presetApi = getBool("preset-api");
    }
}
